package Server;

import iLogger.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;



public class ClientListener {
      // Se crea el socket servidor
      ServerSocket socketServidor = null; 
      EventReceiver answerer;
      
      
      public ClientListener(int listeningPort, EventReceiver answerer) throws IOException
      {
          this.answerer = answerer;
          System.out.println("Creando Listener en " + listeningPort + "\n");
          socketServidor = new ServerSocket(listeningPort);
      }

      public ClientListener(int listeningPort, int maxListeningPort, EventReceiver answerer) throws IOException
      {
          this.answerer = answerer;
          
          boolean created = false;
          while(!created) 
          try {
            created=true;  
            socketServidor = new ServerSocket(listeningPort);
            } catch (IOException ex) {
                listeningPort++;                      
                created=false;
                if(listeningPort>=maxListeningPort){
                    throw(ex);
                }
              }                    
          System.out.println("Creando Listener en " + socketServidor.getLocalPort());
      }
      
      public void start()
      {
                    
        Thread t = new Thread(new Runnable() {
            
           //DataInputStream is = null; 
           //PrintStream os = null;
           String line;
           
            public void run()
            {
                iLogger.log("Escuchando puerto " + socketServidor.getLocalSocketAddress());               
                
                while(true){                                        
                    try {
                        Socket cliente = socketServidor.accept();
                        BufferedReader d = new BufferedReader(new InputStreamReader(cliente.getInputStream()));        
                        line = d.readLine();
                        if (line!=null)
                        {
                    		answerer.receiveMessage(line, cliente);
                        }
	                   d.close();
	                   cliente.close();
	                    
                    } catch (IOException ex) {
                        Logger.getLogger(ClientListener.class.getName()).log(Level.SEVERE, null, ex);
                    }                    
                }
            }
        });
        t.start();
        }    
      
      public int getLocalPort() {
            return socketServidor.getLocalPort();
      }
      
      
      
     
} 
